package com.hdoit.ares.logical.insu.service.impl;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.acc.service.IAwardSettingService;
import com.hdoit.ares.logical.brokerage.model.BrokerageRecord;
import com.hdoit.ares.logical.brokerage.service.IBrokerageRecordService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.insu.dao.IFanhuaAccidentDao;
import com.hdoit.ares.logical.insu.model.FanhuaAccident;
import com.hdoit.ares.logical.insu.service.IFanhuaAccidentService;
import com.hdoit.ares.logical.insu.service.IInsuranceService;
import com.hdoit.ares.logical.policy.service.IListPolicyService;
import com.hdoit.ares.logical.tp.zzb.model.AccidentCallback;
import com.hdoit.ares.logical.viewmodel.insu.FanhuaAccidentSearch;
import com.hdoit.ares.selfcommon.enums.acc.InsuranceType;
import com.hdoit.ares.selfcommon.utils.ExpressionUtil;
import com.tennetcn.common.dao.base.impl.SuperService;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.xiaoleilu.hutool.json.JSONUtil;
/**
 * @author      caochengmeng
 * @email       
 * @createtime  2017年12月10日 23:03:42
 * @comment
 */
@Component
public class FanhuaAccidentServiceImpl extends SuperService<FanhuaAccident> implements IFanhuaAccidentService{
	
	private IFanhuaAccidentDao fanhuaAccidentDao;
	
	public IFanhuaAccidentDao getAccidentInsuranceDao() {
		return fanhuaAccidentDao;
	}
	@Resource
	public void setAccidentInsuranceDao(IFanhuaAccidentDao fanhuaAccidentDao) {
		this.fanhuaAccidentDao = fanhuaAccidentDao;
	}
	
	private IAwardSettingService awardSettingService;
	public IAwardSettingService getAwardSettingService() {
		return awardSettingService;
	}
	@Resource
	public void setAwardSettingService(IAwardSettingService awardSettingService) {
		this.awardSettingService = awardSettingService;
	}

	private ICustomerService customerService;
	
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	private IInsuranceService insuranceService;
	public IInsuranceService getInsuranceService() {
		return insuranceService;
	}
	@Resource
	public void setInsuranceService(IInsuranceService insuranceService) {
		this.insuranceService = insuranceService;
	}
	
	private IBrokerageRecordService brokerageRecordService;
	public IBrokerageRecordService getBrokerageRecordService() {
		return brokerageRecordService;
	}
	@Resource
	public void setBrokerageRecordService(IBrokerageRecordService brokerageRecordService) {
		this.brokerageRecordService = brokerageRecordService;
	}
	
	private IListPolicyService listPolicyService;
	public IListPolicyService getListPolicyService() {
		return listPolicyService;
	}
	@Resource
	public void setListPolicyService(IListPolicyService listPolicyService) {
		this.listPolicyService = listPolicyService;
	}
	
	@Override
	public List<FanhuaAccident> queryAllAccidentInsurance(String customerId) {
		return fanhuaAccidentDao.queryAllAccidentInsurance(customerId);
	}

	@Override
	public List<FanhuaAccident> queryNoAccidentInsurance(String customerId) {		
		return fanhuaAccidentDao.queryNoAccidentInsurance(customerId);
	}

	@Override
	public List<FanhuaAccident> queryYesAccidentInsurance(String customerId) {
		return fanhuaAccidentDao.queryYesAccidentInsurance(customerId);
	}

	@Override
	public List<FanhuaAccident> queryReadyAccidentInsurance(String customerId) {
		return fanhuaAccidentDao.queryReadyAccidentInsurance(customerId);
	}
	@Override
	public List<FanhuaAccident> queryList(FanhuaAccidentSearch accidentInsurance, PagerModel pagerModel) {
		return fanhuaAccidentDao.queryList(accidentInsurance,pagerModel);
	}

	@Override
	public List<FanhuaAccident> queryFailAccidentInsurance(String customerId) {		
		return fanhuaAccidentDao.queryFailAccidentInsurance(customerId);
	}
	
	@Override
	public FanhuaAccident queryModelByPolicyNo(String policyNo) {	
		return fanhuaAccidentDao.queryModelByPolicyNo(policyNo);
	}

	// 意外险详情解析
	@Override
	public String accidentCallback(AccidentCallback accidentCallback) throws RuntimeException {
		FanhuaAccident fanhuaAccident = new FanhuaAccident();
		fanhuaAccident.setId(CommonUtils.getKeyId());
		fanhuaAccident.setModelStatus(ModelStatus.add);

		String appntInfoJsonStr = accidentCallback.getAppntInfo();
		if (!StringUtils.isEmpty(appntInfoJsonStr)) {
			Map<String, Object> appntInfoMap = JSONUtil.parseObj(appntInfoJsonStr);
			String appntName = MapUtils.getString(appntInfoMap, "appntName");
			fanhuaAccident.setAppntName(appntName);

			String appntSexName = MapUtils.getString(appntInfoMap, "appntSexName");
			if (!StringUtils.isEmpty(appntSexName)) {
				fanhuaAccident.setAppntSexName(appntSexName);
			}
			fanhuaAccident.setAppntIdType(MapUtils.getString(appntInfoMap, "appntIdType"));
			fanhuaAccident.setAppntIdNo(MapUtils.getString(appntInfoMap, "appntIdNo"));
			fanhuaAccident.setAppntMobile(MapUtils.getString(appntInfoMap, "appntMobile"));
			fanhuaAccident.setAppntEmail(MapUtils.getString(appntInfoMap, "appntEmail"));
			fanhuaAccident.setAppntBirthday(MapUtils.getString(appntInfoMap, "appntBirthday"));
		}
		String insuredInfoJsonStr = accidentCallback.getInsuredInfo();
		if (!StringUtils.isEmpty(insuredInfoJsonStr)) {
			Map<String, Object> insuredInfoMap = JSONUtil.parseObj(insuredInfoJsonStr);
			System.err.println("insuredInfoMap:" + insuredInfoMap);
			fanhuaAccident.setInsuredName(MapUtils.getString(insuredInfoMap, "insuredName"));
			fanhuaAccident.setInsuredAppntShip(MapUtils.getString(insuredInfoMap, "insuredAppntShip"));
			fanhuaAccident.setInsuredIdType(MapUtils.getString(insuredInfoMap, "insuredIdType"));
			fanhuaAccident.setInsuredIdNo(MapUtils.getString(insuredInfoMap, "insuredIdNo"));
			fanhuaAccident.setInsuredSex(MapUtils.getString(insuredInfoMap, "insuredSex"));
			fanhuaAccident.setInsuredBirthday(MapUtils.getString(insuredInfoMap, "insuredBirthday"));
			fanhuaAccident.setInsuredMobile(MapUtils.getString(insuredInfoMap, "insuredMobile"));
			fanhuaAccident.setInsuredEmail(MapUtils.getString(insuredInfoMap, "insuredEmail"));
		}
		String orderInfoJsonStr = accidentCallback.getOrderInfo();
		if (!StringUtils.isEmpty(orderInfoJsonStr)) {
			System.err.println("orderInfoJsonStr:" + orderInfoJsonStr);
			Map<String, Object> orderInfoMap = JSONUtil.parseObj(orderInfoJsonStr);
			fanhuaAccident.setOrderState(MapUtils.getString(orderInfoMap, "orderState"));
			fanhuaAccident.setOrderId(MapUtils.getString(orderInfoMap, "orderId"));
			fanhuaAccident.setOrderNum(MapUtils.getString(orderInfoMap, "orderNum"));
			fanhuaAccident.setTotalAmount(MapUtils.getString(orderInfoMap, "totalAmount"));
			try {
				String submitTime = MapUtils.getString(orderInfoMap, "submitTime");
				System.err.println("submitTime:" + submitTime);
				if (!StringUtils.isEmpty(submitTime)) {
					fanhuaAccident.setSubmitTime(DateUtils.parseDateTime(submitTime));
				}
				String startTime = MapUtils.getString(orderInfoMap, "startTime");
				System.err.println("startTime:" + startTime);
				if (!StringUtils.isEmpty(startTime)) {
					fanhuaAccident.setStartTime(DateUtils.parseDateTime(startTime));
				}
				String endTime = MapUtils.getString(orderInfoMap, "endTime");
				if (!StringUtils.isEmpty(endTime)) {
					fanhuaAccident.setEndTime(DateUtils.parseDateTime(endTime));
				}
			} catch (Exception e) {
				e.getStackTrace();
				System.err.println("save time error");
			}
			String recommendId = MapUtils.getString(orderInfoMap, "recommendId");
			String[] recommed = recommendId.split("_");
			String customerId = recommed[0];
			String prodId = recommed[1];
			fanhuaAccident.setCustomerId(customerId);
			fanhuaAccident.setProdId(prodId);
			fanhuaAccident.setInsureComName(MapUtils.getString(orderInfoMap, "insureComName"));
			fanhuaAccident.setProductId(MapUtils.getString(orderInfoMap, "productId"));
			fanhuaAccident.setProductName(MapUtils.getString(orderInfoMap, "productName"));
		}
		String policyInfoJsonStr = accidentCallback.getPolicyInfo();
		if (!StringUtils.isEmpty(policyInfoJsonStr)) {
			Map<String, Object> policyInfoMap = JSONUtil.parseObj(policyInfoJsonStr);
			fanhuaAccident.setAppStatus(MapUtils.getString(policyInfoMap, "appStatus"));
			fanhuaAccident.setPolicyNo(MapUtils.getString(policyInfoMap, "policyNo"));
			fanhuaAccident.setDownloadURL(MapUtils.getString(policyInfoMap, "downloadURL"));
		}
		if (!applyChange(fanhuaAccident)) {
			throw new RuntimeException("accidentInsurance save error");
		}
		//游客购买产品确定上下级关系
		Customer buyCustomer = customerService.queryModel(fanhuaAccident.getCustomerId());
		if(buyCustomer.getRefereeIdentity()<=0){
			if(!StringUtils.isEmpty(buyCustomer.getBuyRefreeIdentity())){
				Customer refreeCustomer = customerService.queryModelByUserIdentity(buyCustomer.getBuyRefreeIdentity());
				buyCustomer.setRefereeId(refreeCustomer.getId());
				buyCustomer.setRefereeIdentity(refreeCustomer.getUserIdentity());
				buyCustomer.setRegion(refreeCustomer.getRegion());
				buyCustomer.setUpdateRegionDate(DateUtils.getCurrent());
				buyCustomer.setModelStatus(ModelStatus.update);
				customerService.applyChange(buyCustomer);
			} 
		}
		if(!listPolicyService.setFanhuaAccidentPolicy(fanhuaAccident)){
			throw new RuntimeException("fanhuaAccidentPolicy set error");
		}
		
		if (("1").equals(fanhuaAccident.getAppStatus())) {
			BrokerageRecord brokerageRecord = new BrokerageRecord();
			Double proportion = insuranceService.queryModel(fanhuaAccident.getProdId()).getTotalProportion();
			String totalAmount = fanhuaAccident.getTotalAmount();
			brokerageRecord.setId(CommonUtils.getKeyId());
			brokerageRecord.setBrokerage(Double.valueOf(totalAmount));
			
			double tax = ExpressionUtil.stringToDouble((awardSettingService.queryModelByHC("tax", InsuranceType.NotCar).getExpression()),0.00);
			
			Double taxPercent = new BigDecimal(totalAmount).multiply(new BigDecimal(String.valueOf(proportion))).multiply(new BigDecimal(String.valueOf(tax))).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
			brokerageRecord.setTaxPercent(taxPercent);
			brokerageRecord.setUserId(fanhuaAccident.getCustomerId());
			brokerageRecord.setRecordDate(fanhuaAccident.getSubmitTime());
			brokerageRecord.setCurrency("元");
			brokerageRecord.setCompanyName(fanhuaAccident.getInsureComName());

			// 意外险犹豫期
			Calendar nowcalendar = Calendar.getInstance();
			Calendar startDatecalendar = Calendar.getInstance();
			nowcalendar.setTime(DateUtils.getCurrent());
			startDatecalendar.setTime(fanhuaAccident.getStartTime());
			int day = DateUtils.getDaysBetween(nowcalendar, startDatecalendar);
			brokerageRecord.setHesitateDate(day);

			// 订单号保单号
			brokerageRecord.setOrderSn(fanhuaAccident.getOrderId());
			brokerageRecord.setPolicyNo(fanhuaAccident.getPolicyNo());

			brokerageRecord.setProductId(fanhuaAccident.getProdId());
			brokerageRecord.setProportion(proportion);
			brokerageRecord.setRecordDate(DateUtils.getCurrent());
			brokerageRecord.setModelStatus(ModelStatus.add);
			if (!brokerageRecordService.applyChange(brokerageRecord, InsuranceType.NotCar)) {
				throw new RuntimeException("brokerageRecord save error");
			}
		}
		return "ok";
	}
}
